/*
 * Copyright 2012-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.context.config;

import org.springframework.boot.cloud.CloudPlatform;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;
import org.springframework.core.style.ToStringCreator;

/**
 * 在确定何时激活由 {@link ConfigDataEnvironmentContributor 贡献的}
 * {@link ConfigData} 时使用的上下文信息。
 *
 * @author Phillip Webb
 */
class ConfigDataActivationContext {

	private final CloudPlatform cloudPlatform;

	private final Profiles profiles;

	/**
	 * 在任何 profile 被激活之前创建一个新的
	 * {@link ConfigDataActivationContext} 实例。
	 *
	 * @param environment 源环境对象
	 * @param binder 提供对相关配置数据贡献访问的绑定器
	 */
	ConfigDataActivationContext(Environment environment, Binder binder) {
		this.cloudPlatform = deduceCloudPlatform(environment, binder);
		this.profiles = null;
	}

	/**
	 * 使用给定的 {@link CloudPlatform} 和 {@link Profiles} 创建一个新的
	 * {@link ConfigDataActivationContext} 实例。
	 *
	 * @param cloudPlatform 云平台
	 * @param profiles 当前的 profiles
	 */
	ConfigDataActivationContext(CloudPlatform cloudPlatform, Profiles profiles) {
		this.cloudPlatform = cloudPlatform;
		this.profiles = profiles;
	}

	private CloudPlatform deduceCloudPlatform(Environment environment, Binder binder) {
		for (CloudPlatform candidate : CloudPlatform.values()) {
			if (candidate.isEnforced(binder)) {
				return candidate;
			}
		}
		return CloudPlatform.getActive(environment);
	}

	/**
	 * 返回一个带有特定 profiles 的新 {@link ConfigDataActivationContext} 实例。
	 *
	 * @param profiles 要设置的 profiles
	 * @return 带有指定 profiles 的新 {@link ConfigDataActivationContext}
	 */
	ConfigDataActivationContext withProfiles(Profiles profiles) {
		return new ConfigDataActivationContext(this.cloudPlatform, profiles);
	}

	/**
	 * 返回当前激活的 {@link CloudPlatform}，如果没有则返回 {@code null}。
	 *
	 * @return 当前激活的云平台，或 {@code null}
	 */
	CloudPlatform getCloudPlatform() {
		return this.cloudPlatform;
	}

	/**
	 * 如果 profile 信息可用，则返回该信息。
	 *
	 * @return profile 信息，或 {@code null}
	 */
	Profiles getProfiles() {
		return this.profiles;
	}

	@Override
	public String toString() {
		ToStringCreator creator = new ToStringCreator(this);
		creator.append("cloudPlatform", this.cloudPlatform);
		creator.append("profiles", this.profiles);
		return creator.toString();
	}

}
